package io.quarkus.hibernate.orm.deployment.integration;

import org.hibernate.bytecode.enhance.spi.DefaultEnhancementContext;
import org.hibernate.bytecode.enhance.spi.UnloadedField;
import org.hibernate.bytecode.enhance.spi.UnsupportedEnhancementStrategy;

public final class QuarkusEnhancementContext extends DefaultEnhancementContext {

    public static final QuarkusEnhancementContext INSTANCE = new QuarkusEnhancementContext();

    private QuarkusEnhancementContext() {
        //do not invoke, use INSTANCE
    }

    @Override
    public boolean doBiDirectionalAssociationManagement(final UnloadedField field) {
        //Don't enable automatic association management as it's often too surprising.
        //Also, there's several cases in which its semantics are of unspecified,
        //such as what should happen when dealing with ordered collections.
        return false;
    }

    @Override
    public ClassLoader getLoadingClassLoader() {
        //This shouldn't matter as we delegate resource location to QuarkusClassFileLocator;
        //make sure of this:
        throw new IllegalStateException("The Classloader of the EnhancementContext should not be used");
    }

    @Override
    public UnsupportedEnhancementStrategy getUnsupportedEnhancementStrategy() {
        // We expect model classes to be enhanced.
        // Lack of enhancement could lead to many problems,
        // from bad performance, to Quarkus-specific optimizations causing errors/data loss,
        // to incorrect generated bytecode (references to non-existing methods).
        // However, the built-in checks in Hibernate ORM to detect cases where enhancement doesn't work
        // seem to have many false positives -- in particular they assume property access for
        // mapped-superclasses and embeddables, because the access type cannot be determined locally for those,
        // which leads to reporting some very valid setups as invalid.
        // So, since we cannot accurately detect that something is wrong, we won't even try.
        // Longer-term, the solution is just to make bytecode enhancement work even in these cases:
        // https://hibernate.atlassian.net/browse/HHH-18825
        return UnsupportedEnhancementStrategy.LEGACY;
    }

}
